package com.db.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.db.common.exception.ServiceException;
import com.db.common.pojo.TreeNode;
import com.db.dao.SysMenuDao;
import com.db.pojo.SysMenu;
import com.db.service.SysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SysMenuServiceImpl implements SysMenuService {

    @Autowired
    private SysMenuDao sysMenuDao;

    @Override
    public List<SysMenu> findObjects() {
        List<SysMenu> list = sysMenuDao.selectList(null);
        return list;
    }

    @Override
    public void deleteById(Integer id) {
        //若存在子菜单,则无法删除
        QueryWrapper<SysMenu> wrapper = new QueryWrapper<>();
        wrapper.eq("parentId", id);
        Integer rows = sysMenuDao.selectCount(wrapper);
        if (rows > 0)
            throw new ServiceException("有子菜单,无法删除");

        sysMenuDao.deleteById(id);
    }

    @Override
    public List<TreeNode> findTree() {
        List<SysMenu> sysMenus = sysMenuDao.selectList(null);

        List<TreeNode> list = new ArrayList<>();
        for (SysMenu sysMenu :
                sysMenus) {
            TreeNode treeNode = new TreeNode();
            treeNode.setId(sysMenu.getId());
            treeNode.setName(sysMenu.getName());
            treeNode.setParentId(sysMenu.getParentId());
            list.add(treeNode);
        }

        return list;
    }

    @Override
    public void insertObject(SysMenu sysMenu) {
        sysMenuDao.insert(sysMenu);
    }

    @Override
    public void updateObject(SysMenu sysMenu) {
        sysMenuDao.updateById(sysMenu);
    }
}
